<!-- 新增/编辑指标 -->
<template>
  <a-drawer
    width="45%"
    :visible="props.visible"
    @ok="handleOk"
    @cancel="handleCancel"
    draggable
    title-align="center"
    unmountOnClose
  >
    <template #title> {{ props.data?.id ? '编辑指标' : '新增指标' }} </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules" auto-label-width>
        <a-form-item label="目标(O)" field="name" show-colon>
          <a-input v-model="formData.name" />
        </a-form-item>
        <a-form-item
          label="(O)权重/分值"
          field="weight"
          show-colon
          :tooltip="`最大权重不能超过100`"
        >
          <a-input-number
            v-model="formData.weight"
            :max="100"
            :precision="2"
            :min="0.01"
            hide-button
            ><template #suffix>%</template>
          </a-input-number>
          <!-- <a-select
            v-model="formData.weightType"
            :style="{ width: '80px' }"
            placeholder="权重类型"
          >
            <a-option
              v-for="item of weightTypeOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.lable }}</a-option
            >
          </a-select> -->
        </a-form-item>
        <a-form-item
          label="关键成果(KR)"
          field="personnelKeyResultsIndexLibrary"
          show-colon
        >
          <a-table :data="formData.personnelKeyResultsIndexLibrary" stripe>
            <template #columns>
              <a-table-column title="关键成果(KR)" data-index="">
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`personnelKeyResultsIndexLibrary.${rowIndex}.result`"
                    hide-label
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                  >
                    <a-textarea
                      v-model="record.result"
                      show-word-limit
                      :max-length="50"
                      :auto-size="{
                        minRows: 2
                      }"
                    ></a-textarea>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="指标权重(%)" data-index="">
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`personnelKeyResultsIndexLibrary.${rowIndex}.indexWeight`"
                    hide-label
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      },
                      {
                        validator: validateKrsWeight
                      }
                    ]"
                  >
                    <a-input-number
                      v-model="record.indexWeight"
                      hide-button
                      :precision="2"
                      style="width: 100px"
                      :max="
                        krsMaxWeight <= 100 && krsMaxWeight >= 0
                          ? 100 - krsMaxWeight + record.indexWeight
                          : record.indexWeight
                      "
                    ></a-input-number>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="操作" data-index="" :width="100">
                <template #cell="{ record, rowIndex }">
                  <IconFont
                    type="icon-add-def"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                    @click="add(rowIndex)"
                  />
                  <a-tooltip
                    content="删除"
                    v-if="formData.personnelKeyResultsIndexLibrary.length > 1"
                  >
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="del(record, rowIndex)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-form-item>
        <!-- <a-form-item label="备注" field="remark" show-colon>
          <a-textarea
            v-model="formData.remark"
            show-word-limit
            :max-length="50"
            :auto-size="{
              minRows: 4
            }"
          ></a-textarea>
        </a-form-item> -->
        <a-form-item label="状态" field="" show-colon>
          <a-switch
            v-model="formData.status"
            :checked-value="1"
            :unchecked-value="2"
            size="medium"
          >
            <template #checked> 启动 </template>
            <template #unchecked> 停止 </template>
          </a-switch>
        </a-form-item>
      </a-form>
      <!-- <CountSetting v-model:visible="countSettingVisiable"></CountSetting> -->
    </div>
    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk">确认</a-button>
        <a-button type="primary" @click="continueAdd">确认并继续新增</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash';
import { useAssessmentToolStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import { OkrIndex } from '@/apis/management/performance/baseSetting/template/type';
import { GetOkrIndexRepeat } from '@/apis/management/performance/baseSetting/template';
import { PersonnelAbilityQualityIndexLibrary } from '@/apis/human/base/variationManager/probation/type';
import { delKeyResult } from '@/apis/human/base/variationManager/probation';
import { useVModel } from '@vueuse/core';

const toolStore = useAssessmentToolStore();
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data?: OkrIndex; // 传进来的数据,
    delIds?: number[]; // 删除的成果id
  }>(),
  {}
);

const emits = defineEmits(['update:visible', 'okrIndexEmit', 'update:delIds']);
const modelDeletedResultIds = useVModel(props, 'delIds', emits);
let refForm = ref();
let countSettingVisiable = ref(false); // 是否设置计算公式弹出框
const formData = useVModel(props, 'data', emits);
const weightTypeOptions = Object.freeze([
  { value: 1, lable: '%' },
  { value: 2, lable: '分' }
]);
// 原始数据
const originData = {
  target: undefined, // 目标O
  weight: 0, // (O)权重/分值
  // 关键成果krs
  personnelKeyResultsIndexLibrary: [
    {
      result: '',
      indexWeight: 0
      // scorers
    }
  ],
  // result: [
  //   {
  //     name: '',
  //     weight: undefined
  //   }
  // ], // 关键成果krs
  require: '', // 完成目标及时限要求
  standard: undefined, // 评分标准
  // weight: '', // 指标权重
  dataSource: undefined, // 评分人（userid）
  upper: '', // 评分上限
  remark: '', // 备注
  personne: 1, // 评分人是否开启 1开 2否
  // dimensionaId: '', // 维度id
  way: 1, // 考核评分 1直接输入
  hid: undefined // 目标id
};

// 校验kr权重
const validateKrsWeight = (val: number, cb: any) => {
  if (krsMaxWeight.value - val === 100)
    cb('权重总和已经达到100，若要继续新增请先调整其他的权重!');
};

// 校验(O)权重/分值
const validateweight = (val: number, cb: any) => {
  // console.log('====================================');
  // console.log(props.maxWeight);
  // console.log(props.data);
  // console.log('====================================');
  // if (
  //   props.maxWeight - (props?.data?.weight ? props?.data?.weight : 0) ===
  //   100
  // )
  //   cb('权重总和已经达到100，若要继续新增请先调整其他的权重!');
};
/**
 * 查重
 */
const validateName = async (value: any, cb: any) => {
  if (value === props.data?.name) return;
  const res = await GetOkrIndexRepeat({ name: formData.value.name });
  if (res?.code === 400) {
    cb('名称已存在!');
  }
};
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  weight: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateweight
    }
  ],
  personnelKeyResultsIndexLibrary: [
    {
      required: true,
      message: '请输入'
    }
  ]
  // indexWeight: [
  //   {
  //     required: true,
  //     message: '请输入'
  //   }
  // ]
});

// watch(
//   () => props.visible,
//   (newVal: boolean) => {
//     // 如果是编辑，则赋值给formData
//     if (newVal) {
//       if (props.data) {
//         formData.value = cloneDeep(props.data);

//         isShowContinueBtn.value = false;
//       } else {
//         krsMaxWeight.value = 0;
//         formData.value = cloneDeep(props.data);
//       }
//       // 如果设置了加权则要设置总分上限
//       // formData.value.upper =
//       //   toolStore.getCalculate === 2 && toolStore.upperLimit === 1
//       //     ? toolStore.getUpperScore * props.weight * 0.01
//       //     : undefined;
//     } else {
//       isShowContinueBtn.value = true;
//       formData.value = cloneDeep(originData);
//       krsMaxWeight.value = 0;
//     }
//   }
// );

// let krsMaxWeight = ref(0); // 储存kr权重，最高不能超过100

const krsMaxWeight = computed((val: number, _: Event, index: number) => {
  const res = formData.value.personnelKeyResultsIndexLibrary.reduce(
    (pre: any, cur: any) => {
      const temp = cur.indexWeight > 0 ? cur.indexWeight : 0;
      return pre + temp;
    },
    0
  );
  return res;
});

// 新增一项
const add = (index: number) => {
  krsMaxWeight.value = formData.value.personnelKeyResultsIndexLibrary.reduce(
    (pre: any, cur: any) => pre + cur.indexWeight,
    0
  );

  formData.value.personnelKeyResultsIndexLibrary.splice(index + 1, 0, {
    result: '',
    indexWeight: 0
  });
};

const del = async (data: OkrIndex, index: number) => {
  if (data.id) {
    modelDeletedResultIds.value?.push(data.id);
    // await delKeyResult({ ids: [data.id] });
  }
  krsMaxWeight.value -=
    formData.value.personnelKeyResultsIndexLibrary[index].indexWeight;
  formData.value.personnelKeyResultsIndexLibrary.splice(index, 1);
  // emits('okrIndexEmit', cloneDeep(formData.value));
};

const handleOk = async () => {
  // console.log(formData.value);
  // return;

  if (await refForm.value.validate()) {
    return;
  }
  if (
    formData.value.personnelKeyResultsIndexLibrary.reduce(
      (pre: any, cur: any) => pre + cur.indexWeight,
      0
    ) !== 100
  ) {
    Message.error('关键成果(KR)里的KR权重值总和必须为100！');
    return;
  }
  // const temp: any = [];
  // formData.value.result.forEach((item: any) => {
  //   temp.push({
  //     ...formData.value,
  //     resultName: item.name,
  //     resultWeight: item.weight
  //   });
  // });
  emits('okrIndexEmit', cloneDeep(formData.value));
  emits('update:visible', false);
};

const continueAdd = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  if (
    formData.value.personnelKeyResultsIndexLibrary.reduce(
      (pre: any, cur: any) => pre + cur.indexWeight,
      0
    ) !== 100
  ) {
    Message.error('关键成果(KR)里的KR权重值总和必须为100！');
    return;
  }
  emits('okrIndexEmit', cloneDeep(formData.value), true);
  emits('update:visible', true);
  formData.value = cloneDeep(originData);
  // 如果设置了加权则要设置总分上限
  // formData.value.upper =
  //   toolStore.getCalculate === 2 && toolStore.upperLimit === 1
  //     ? toolStore.getUpperScore * props.weight * 0.01
  //     : undefined;
};

const handleCancel = () => {
  modelDeletedResultIds.value = [];

  emits('update:visible', false);
};
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
